package com.boc.langxiang.ui.fragment.customized;


import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.boc.langxiang.R;
import com.boc.langxiang.contract.ImageContract;
import com.boc.langxiang.contract.customized.CustomizedPostContract;
import com.boc.langxiang.entity.bean.PhotoBean;
import com.boc.langxiang.entity.events.CityReadDoneEvent;
import com.boc.langxiang.entity.request.CustomizedRequest;
import com.boc.langxiang.manager.CityManeger;
import com.boc.langxiang.manager.PicassoImageLoader;
import com.boc.langxiang.manager.UserInfoManager;
import com.boc.langxiang.presenter.ImagePresenter;
import com.boc.langxiang.presenter.customized.CustomizedPostPresenter;
import com.boc.langxiang.ui.dialog.CustomizedResultDialog;
import com.boc.langxiang.ui.fragment.BaseFragment;
import com.boc.langxiang.util.KeyBoardUtil;
import com.boc.langxiang.util.StringUtil;
import com.boc.langxiang.util.T;
import com.boc.pickview.OptionsPickerView;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.loader.GlideImageLoader;
import com.lzy.imagepicker.ui.ImageGridActivity;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * A simple {@link Fragment} subclass.
 */
public class CustomizedFragment extends BaseFragment implements View.OnClickListener, CustomizedPostContract.View {


    @BindView(R.id.tool_bar)
    RelativeLayout toolBar;
    @BindView(R.id.photos_recycler)
    RecyclerView photosRecycler;
    @BindView(R.id.address_tv)
    TextView addressTv;
    @BindView(R.id.select_district)
    RelativeLayout selectDistrict;
    @BindView(R.id.commit_btn)
    Button commitBtn;
    @BindView(R.id.size_edt)
    EditText sizeEdt;
    @BindView(R.id.material_edt)
    EditText materialEdt;
    @BindView(R.id.content_edt)
    EditText contentEdt;

    private OptionsPickerView mOptionsPickerView;

    private String provinceS;
    private String cityS;
    private String districtS;

//    private View addPhotoView;

    private List<PhotoBean> mPhotoList;

    private PhotoAdapter mPhotoAdapter;

    private ImagePicker mImagePicker;

    private final PhotoBean mAddPhotoItem = new PhotoBean();

    private boolean mIsOnActResult;


    private CustomizedPostPresenter mPresenter;

    private CustomizedRequest mRequest;

    public CustomizedFragment() {
        // Required empty public constructor
    }

    private boolean isShowing = false;

    public static CustomizedFragment newInstance() {
        CustomizedFragment customizedFragment = new CustomizedFragment();
        return customizedFragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_customized, container, false);

        ButterKnife.bind(this, view);
        EventBus.getDefault().register(this);
        mPresenter = new CustomizedPostPresenter(this);
        mRequest = new CustomizedRequest();
        initViews();
        return view;
    }

    private void initViews() {
        selectDistrict.setOnClickListener(this);
        photosRecycler.setLayoutManager(new GridLayoutManager(mContext, 3));
        mPhotoList = new ArrayList<>();
        mPhotoList.add(mAddPhotoItem);
        mPhotoAdapter = new PhotoAdapter(mPhotoList);
        photosRecycler.setAdapter(mPhotoAdapter);

        sizeEdt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                mRequest.setSize(s.toString());
            }
        });

        materialEdt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                mRequest.setMaterial(s.toString());
            }
        });

        contentEdt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                mRequest.setContent(s.toString());
            }
        });


        commitBtn.setOnClickListener(this);
        updateList();
    }

    private ImageItem mImageItem;

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 100 && resultCode == ImagePicker.RESULT_CODE_ITEMS && data != null) {
            ArrayList<ImageItem> tempImages = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
            mImageItem = tempImages.get(0);
            mIsOnActResult = true;
//            uploadImage(item);
        }
    }

    private void uploadImage(ImageItem imageItem) {
        final PhotoBean photoBean = new PhotoBean();
        photoBean.setPhoto("file://" + imageItem.path);
        new ImagePresenter(new ImageContract.View() {
            @Override
            public void uploadFileFailed() {
                T.showShort(mContext, "上传失败，请重新选择图片");
            }

            @Override
            public void uploadFileSuccess(String content) {
                photoBean.setId(content);
//                mPhotoAdapter.getData().add(photoBean);
//                mPhotoAdapter.notifyDataSetChanged();
                mPhotoList.add(photoBean);
                updateList();
            }

            @Override
            public void showLoading() {
                showProgressDialog("正在上传图片");
            }

            @Override
            public void hideLoading() {
                CustomizedFragment.this.hideDialog();
            }

            @Override
            public void onError(String code, String msg) {
                T.showShort(mContext, msg);
            }
        }).uploadFile(imageItem.path);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.select_district:
                KeyBoardUtil.closeKeybord(getActivity());
                CityManeger.getCity();
                break;
            case R.id.commit_btn:
                commit();
                break;
        }
    }

    private void commit() {
        if (isLogin()) {
            mRequest.setPhone(UserInfoManager.getInstance().getUserInfo().getPhone());
            List<PhotoBean> photolist = mPhotoList;
            photolist.remove(mAddPhotoItem);
            if (photolist.size() > 0) {
                List<String> photos = new ArrayList<>();
                for (int i = 0; i < photolist.size(); i++) {
                    photos.add(photolist.get(i).getId());
                }
                StringBuffer photoIds = new StringBuffer();
                for (int i = 0; i < photos.size(); i++) {
                    if (i != photos.size() - 1) {
                        photoIds.append(photos.get(i) + ",");
                    } else {
                        photoIds.append(photos.get(i));
                    }
                }
                String ids = photoIds.toString();
                mRequest.setPhoto(ids);
            } else {
                T.showShort(mContext, "请选择图片");
                return;
            }
            if (StringUtil.isEmpty(mRequest.getSize())) {
                T.showShort(mContext, "请输入尺寸信息");
                return;
            }

            if (StringUtil.isEmpty(mRequest.getMaterial())) {
                T.showShort(mContext, "请输入材质内容");
                return;
            }
            if (StringUtil.isEmpty(mRequest.getArea())) {
                T.showShort(mContext, "请选择收货地区");
                return;
            }

            mPresenter.post(mRequest);

        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onCityReadDoneEvent(CityReadDoneEvent event) {
        if (mOptionsPickerView == null) {
            mOptionsPickerView = new OptionsPickerView(mContext);
        }
        mOptionsPickerView.setPicker(CityManeger.provinceNames, CityManeger.cityNames, CityManeger.distirctNames, true);
        mOptionsPickerView.setTitle("选择地点");
        mOptionsPickerView.setCyclic(false, false, false);
        mOptionsPickerView.setSelectOptions(0, 0, 0);
        mOptionsPickerView.setOnoptionsSelectListener(new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3) {
                String area = "";
                if (CityManeger.distirctList.get(options1).get(option2).size() != 0) {
                    area = CityManeger.provinceList.get(options1).getName()
                            + CityManeger.cityList.get(options1).get(option2).getName()
                            + CityManeger.distirctList.get(options1).get(option2).get(options3).getName();
//                    districtId = "" + CityManeger.distirctList.get(options1).get(option2).get(options3).getId();
                } else {
                    area = CityManeger.provinceList.get(options1).getName()
                            + CityManeger.cityList.get(options1).get(option2).getName();
//                    districtId = "" + CityManeger.cityList.get(options1).get(option2).getId();
                }
                provinceS = CityManeger.provinceList.get(options1).getName();
                cityS = CityManeger.cityList.get(options1).get(option2).getName();
                districtS = CityManeger.distirctList.get(options1).get(option2).get(options3).getName();

                addressTv.setText(area);
                mRequest.setArea(area);
            }
        });
        if (isShowing) {
            mOptionsPickerView.show();
        }
    }

    @Override
    public void onSuccess() {
        mRequest = new CustomizedRequest();
        mPhotoList.clear();
        mPhotoList.add(mAddPhotoItem);
        mPhotoAdapter.notifyDataSetChanged();
        addressTv.setText("");
        provinceS = null;
        cityS = null;
        districtS = null;

        addressTv.setText("");
        sizeEdt.setText("");
        contentEdt.setText("");
        materialEdt.setText("");
        new CustomizedResultDialog(mContext).show();

    }

    @Override
    public void showLoading() {
        showProgressDialog("正在提交");
    }

    @Override
    public void hideLoading() {
        super.hideDialog();
    }

    @Override
    public void onError(String code, String msg) {
        T.showShort(mContext, msg);
    }


    private class PhotoAdapter extends BaseQuickAdapter<PhotoBean> {


        public PhotoAdapter(List<PhotoBean> data) {
            super(R.layout.customized_photo_item, data);
        }

        @Override
        protected void convert(BaseViewHolder helper, final PhotoBean item) {
//            PicassoImageLoader.getInstance().displayUrlImage(mContext, item.getPhoto(), (ImageView) helper.getView(R.id.photo_iv));
//            helper.getView(R.id.delete_iv).setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View v) {
//                    remove(getData().indexOf(item));
//                    updateList();
//                }
//            });
            if (item.equals(mAddPhotoItem)) {
                helper.getView(R.id.photo_content).setVisibility(View.GONE);
                helper.getView(R.id.add_content).setVisibility(View.VISIBLE);
                helper.getView(R.id.add_iv).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mImagePicker = ImagePicker.getInstance();
                        mImagePicker.setImageLoader(GlideImageLoader.getInstance());
                        mImagePicker.setShowCamera(false);
                        mImagePicker.setMultiMode(false);
                        mImagePicker.setCrop(false);
                        Intent intent = new Intent(mContext, ImageGridActivity.class);
                        startActivityForResult(intent, 100);
                    }
                });
            } else {
                helper.getView(R.id.add_content).setVisibility(View.GONE);
                helper.getView(R.id.photo_content).setVisibility(View.VISIBLE);
                PicassoImageLoader.getInstance().displayUrlImage(mContext, item.getPhoto(), (ImageView) helper.getView(R.id.photo_iv));
                helper.getView(R.id.delete_iv).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        remove(getData().indexOf(item));
                        updateList();
                    }
                });
            }

        }

    }

    private void updateList() {
        if (mPhotoList.size() < 7) {
            mPhotoList.remove(mAddPhotoItem);
            mPhotoList.add(mAddPhotoItem);
        } else {
            mPhotoList.remove(mAddPhotoItem);
        }
        mPhotoAdapter.notifyDataSetChanged();
    }


    @Override
    public void onPause() {
        super.onPause();
        isShowing = false;
    }

    @Override
    public void onResume() {
        super.onResume();
        isShowing = true;
        if (mIsOnActResult) {
            uploadImage(mImageItem);
            mIsOnActResult = false;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
